<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="发起时间" prop="useTime" style="width: 308px">
              <el-date-picker
                v-model="dateRange"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="审批状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择审批状态" clearable>
                <el-option v-for="dict in approval_record_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间" prop="createTime" style="width: 308px">
              <el-date-picker
                v-model="createTimeRange"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['humanresource:hrEntryApply:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['humanresource:hrEntryApply:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['humanresource:hrEntryApply:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['humanresource:hrEntryApply:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="hrEntryApplyList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键" align="center" prop="id" v-if="false" />
        <el-table-column label="发起人" align="center" prop="initialId" fixed="left">
          <template #default="scope">
            <span>{{ scope.row.initialName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="部门" align="center" prop="deptId" fixed="left">
          <template #default="scope">
            <el-tag type="primary" disable-transitions>
              {{ scope.row.deptName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="发起时间" align="center" prop="initialTime" width="120" fixed="left">
          <template #default="scope">
            <span>{{ parseTime(scope.row.initialTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="姓名" align="center" prop="name" />
        <el-table-column label="性别" align="center" prop="sex" :formatter="formatSex"/>
        <el-table-column label="年龄" align="center" prop="age" />
        <el-table-column label="学历" align="center" prop="qualification" width="100"/>
        <el-table-column label="是否婚配" align="center" prop="isMarriage" :formatter="formatIsMarriage"/>
        <el-table-column label="联系方式" align="center" prop="phone" >
          <template #default="scope">
            <el-tooltip :content="scope.row.phone" placement="top" :disabled="!scope.row.phone">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.phone }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="到岗日期" align="center" prop="onboardTime" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.onboardTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="拟录用部门" align="center" prop="hireDeptId" width="120">
          <template #default="scope">
            <el-tag type="primary" disable-transitions>
              {{ scope.row.hireDeptName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="拟录用职位" align="center" prop="hirePosition" width="120">
          <template #default="scope">
            <el-tooltip :content="scope.row.hirePosition" placement="top" :disabled="!scope.row.hirePosition">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.hirePosition }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="定薪标准" align="center" prop="salaryDisplay">
          <template #default="scope">
            <el-tooltip
              :content="scope.row.salaryDisplay"
              placement="top"
              :disabled="!scope.row.salaryDisplay"
            >
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span
                  style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;"
                >
                  {{ scope.row.salaryDisplay }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="120" fixed="right">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="审批状态" align="center" prop="status" fixed="right">
          <template #default="scope">
            <dict-tag :options="approval_record_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['humanresource:hrEntryApply:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['humanresource:hrEntryApply:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改新员工入职材料审批对话框 -->
    <el-dialog 
      :title="dialog.title" 
      v-model="dialog.visible" 
      width="900px" 
      append-to-body
    >
      <template #default>
        <el-form ref="hrEntryApplyFormRef" :model="form" :rules="rules" label-width="140px" label-position="left" style="padding: 20px 0 20px 24px">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="发起人" prop="initialName">
                <el-input v-model="form.initialName" placeholder="请输入发起人名称" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="部门" prop="deptId">
                  <el-tree-select
                    v-model="form.deptId"
                    :data="deptTree"
                    placeholder="请选择申请部门"
                    :props="{ label: 'label', value: 'id', children: 'children' }"
                    check-strictly
                    filterable
                    :default-expand-all="true"
                    style="width: 100%"
                    @visible-change="handleVisibleChange"
                  />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="发起时间" prop="initialTime">
                <el-date-picker clearable
                  v-model="form.initialTime"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择发起时间"
                  style="width: 100%;">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="姓名" prop="name">
                <el-input v-model="form.name" placeholder="请输入面试者姓名" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="性别" prop="sex" required>
                <el-select
                  v-model="form.sex"
                  placeholder="请选择性别"
                  style="width: 100%;"
                >
                  <el-option label="男" :value="1" />
                  <el-option label="女" :value="0" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="年龄" prop="age">
                <el-input v-model="form.age" placeholder="请输入年龄" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="学历" prop="qualification">
                <el-select
                  v-model="form.qualification"
                  placeholder="请选择学历"
                  clearable
                  style="width: 100%;"
                >
                  <el-option label="高中/大专" value="高中/大专" />
                  <el-option label="本科" value="本科" />
                  <el-option label="硕士" value="硕士" />
                  <el-option label="博士" value="博士" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否婚配" prop="isMarriage">
                <el-select
                  v-model="form.isMarriage"
                  placeholder="请选择是否婚配"
                  style="width: 100%;"
                >
                  <el-option label="已婚" :value="1" />
                  <el-option label="未婚" :value="0" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系方式" prop="phone">
                <el-input v-model="form.phone" placeholder="请输入联系方式" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="到岗日期" prop="onboardTime">
                <el-date-picker clearable
                  v-model="form.onboardTime"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择到岗日期"
                  style="width: 100%;">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="拟录用部门" prop="hireDeptId">
                <el-tree-select
                    v-model="form.hireDeptId"
                    :data="deptTree"
                    placeholder="请选择申请部门"
                    :props="{ label: 'label', value: 'id', children: 'children' }"
                    check-strictly
                    filterable
                    :default-expand-all="true"
                    style="width: 100%"
                    @visible-change="handleVisibleChange"
                  />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="拟录用职位" prop="hirePosition">
                <el-input v-model="form.hirePosition" placeholder="请输入拟录用职位" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="定薪标准" prop="salaryRecords">
                <div v-for="(item, index) in form.salaryRecords" :key="index" style="display:flex; gap:8px; align-items:center; margin-bottom:8px;">
                  <!-- 阶段 -->
                  <el-select v-model="item.salaryType" placeholder="请选择阶段" style="flex:0 0 120px;">
                    <el-option label="实习期" value="实习期" />
                    <el-option label="试用期" value="试用期" />
                    <el-option label="转正" value="转正" />
                  </el-select>
                  <!-- 税前/税后 -->
                  <el-select v-model="item.salaryTaxType" placeholder="税前/税后" style="flex:0 0 120px;">
                    <el-option label="税前" value="税前" />
                    <el-option label="税后" value="税后" />
                  </el-select>
                  <!-- 金额 -->
                  <el-input v-model="item.salaryAmount" placeholder="请输入工资金额(元/月)" style="flex:1;" />
                  <!-- 删除按钮 -->
                  <el-button type="danger" icon="el-icon-delete" @click="removeRecord(index)" link>删除</el-button>
                </div>
                <div>
                  <!-- 新增按钮 --> 
                  <el-button style="margin-bottom: 9px;" type="primary" icon="el-icon-plus" @click="addRecord" link>新增</el-button>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="附件上传" prop="attachments">
                <el-checkbox-group v-model="form.attachments">
                  <!-- 新入员工提供（必选） -->
                  <div>
                    <div><strong>新入员工提供（必选）</strong></div>
                    <el-checkbox
                      v-for="item in requiredNewEmployee"
                      :key="item"
                      :label="item"
                    >{{ item }}</el-checkbox>
                  </div>

                  <!-- 入职登记资料（必选） -->
                  <div style="margin-top: 10px;">
                    <div><strong>入职登记资料（必选）</strong></div>
                    <el-checkbox
                      v-for="item in requiredOnboarding"
                      :key="item"
                      :label="item"
                    >{{ item }}</el-checkbox>
                  </div>

                  <!-- 选填 -->
                  <div style="margin-top: 10px;">
                    <div><strong>选填</strong></div>
                    <el-checkbox
                      v-for="item in optionalAttachments"
                      :key="item"
                      :label="item"
                    >{{ item }}</el-checkbox>
                  </div>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="HrEntryApply" lang="ts">
import { listHrEntryApply, getHrEntryApply, delHrEntryApply, addHrEntryApply, updateHrEntryApply } from '@/api/general/humanresources/onboard/entry';
import { HrEntryApplyVO, HrEntryApplyQuery, HrEntryApplyForm, SalaryRecordVO } from '@/api/general/humanresources/onboard/entry/types';
import type { DeptTreeNode } from '@/api/general/administration/seal/types';
import { getDeptTree } from '@/api/general/administration/seal';
import { useUserStore } from '@/store/modules/user';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const hrEntryApplyList = ref<HrEntryApplyVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

// 用户信息
const userStore = useUserStore();

// 部门树初始化
const deptTree = ref<DeptTreeNode[]>([]);
const deptTreeSelectRef = ref();

// 薪资记录
const salaryRecords = reactive<SalaryRecordVO[]>([
  { salaryType: null, salaryTaxType: null, salaryAmount: null } // 初始一条
])


// 引入数据字典
const { adm_item_type, approval_record_status } = toRefs<any>(proxy?.useDict('adm_item_type', 'approval_record_status'));



// 性别映射
const sexMap = {
  0: '女',
  1: '男'
};

const formatSex = (row, column, cellValue) => {
  return sexMap[cellValue] || '';
};

// 是否婚配映射
const isMarriageMap = {
  0: '未婚',
  1: '已婚'
};

// 必填与选填数据
const requiredNewEmployee = [
  '离职证明原件', '身份证复印件', '毕业证书复印件', '学位证复印件', '学信网验真报告'
];
const requiredOnboarding = [
  '应聘登记表', '面试评估意见', '背景调查表', '月度预发工资标准确认单',
  '入职声明与保证书', '入职授权书', '合规承诺书', '入职手续完备表', '入职信息登记表',
  '安全责任承诺书', '劳动合同2份', '保密协议2份', '录用条件确认书', '入职通知函',
  '背景调查表', '新员工录用登记表'
];
const optionalAttachments = [
  '体检证明原件', '银行卡复印件', '照片原件2张', '无离职证明申明', '专业技能资质证书／职称证书复印件'
];

const formatIsMarriage = (row, column, cellValue) => {
  return isMarriageMap[cellValue] || '';
};

// 时间选择器查询参数初始化
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const createTimeRange = ref<[DateModelType, DateModelType]>(['', '']);

const queryFormRef = ref<ElFormInstance>();
const hrEntryApplyFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 本地时间格式化函数
const formatLocalDate = (date = new Date()) => {
  const padZero = num => String(num).padStart(2, '0');
  return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())}`;
};

const initFormData: HrEntryApplyForm = {
  id: undefined,
  initialId: userStore.userId,
  initialName: userStore.name,
  deptId: userStore.deptId,
  deptName: userStore.deptName,
  initialTime: formatLocalDate(),
  name: undefined,
  sex: undefined,
  age: undefined,
  qualification: undefined,
  isMarriage: undefined,
  phone: undefined,
  onboardTime: undefined,
  hireDeptId: undefined,
  hirePosition: undefined,
  salary: undefined,
  salaryRecords: [],
  attachmentName: undefined,
  attachments: [...requiredNewEmployee, ...requiredOnboarding],
  status: undefined,
}
const data = reactive<PageData<HrEntryApplyForm, HrEntryApplyQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    initialId: undefined,
    deptId: undefined,
    initialTime: undefined,
    name: undefined,
    sex: undefined,
    age: undefined,
    qualification: undefined,
    isMarriage: undefined,
    phone: undefined,
    onboardTime: undefined,
    hireDeptId: undefined,
    hirePosition: undefined,
    salary: undefined,
    attachmentName: undefined,
    status: undefined,
    createTime: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "主键不能为空", trigger: "blur" }
    ],
    initialName: [{ required: true, message: '发起人不能为空', trigger: 'blur' }],
    deptId: [{ required: true, message: '请选择申请部门', trigger: 'change' }],
    initialTime: [{ required: true, message: '请选择发起时间', trigger: 'change' }],
    name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
    age: [
      { required: true, message: '请输入年龄', trigger: 'blur' },
      { pattern: /^[0-9]{1,3}$/, message: '年龄必须是数字', trigger: 'blur' }
    ],
    qualification: [{ required: true, message: '请选择学历', trigger: 'change' }],
    isMarriage: [{ required: true, message: '请选择婚姻状况', trigger: 'change' }],
    phone: [
      { required: true, message: '请输入联系方式', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入有效手机号', trigger: 'blur' }
    ],
    onboardTime: [{ required: true, message: '请选择到岗日期', trigger: 'change' }],
    hireDeptId: [{ required: true, message: '请选择拟录用部门', trigger: 'change' }],
    hirePosition: [{ required: true, message: '请输入拟录用职位', trigger: 'blur' }],
    salaryRecords: [
      {
          validator(_: any, value: SalaryRecordVO[], callback: (error?: string) => void) {
            for (let i = 0; i < value.length; i++) {
              const record = value[i];
              if (!record.salaryType) {
                callback(`第${i + 1}条记录：请选择阶段（实习期/试用期/转正）`);
                return;
              }
              if (!record.salaryTaxType) {
                callback(`第${i + 1}条记录：请选择税前/税后`);
                return;
              }
              if (!record.salaryAmount) {
                callback(`第${i + 1}条记录：请输入工资金额`);
                return;
              }
            }
            callback();
          },
          trigger: 'change'
        }
      ],
     attachments: [
      {
        validator(rule, value, callback) {
          const requiredAll = [...requiredNewEmployee, ...requiredOnboarding];
          const missing = requiredAll.filter(item => !value.includes(item));
          if (missing.length > 0) {
            callback(new Error('必填附件未选择完整，请选择所有必填项'));
          } else {
            callback(); // 验证通过
          }
        },
        trigger: 'change'
      }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询新员工入职材料审批列表 */
const getList = async () => {
  loading.value = true;
  try {
    const params = { ...queryParams.value };
    if (dateRange.value?.length === 2) {
      params.params = {
        ...params.params,
        bUseTime: dateRange.value[0]?.toString(),
        eUseTime: dateRange.value[1]?.toString()
      };
    }
    if (createTimeRange.value?.length === 2) {
      params.params = {
        ...params.params,
        beginTime: createTimeRange.value[0]?.toString(),
        endTime: createTimeRange.value[1]?.toString()
      };
    }
    const res = await listHrEntryApply(queryParams.value);
    hrEntryApplyList.value = res.rows.map((item: any) => {
      const newItem = { ...item };
      // 解析 salary 字段为数组
      let salaryArr: any[] = [];
      try {
        salaryArr = typeof item.salary === 'string' ? JSON.parse(item.salary) : [];
      } catch (err) {
        salaryArr = [];
      }
      // 转成显示字符串
      newItem.salaryDisplay = salaryArr
        .map(s => `${s.salaryType || '-'}（${s.salaryTaxType || '-'}）：${s.salaryAmount || '-'}`)
        .join('；');
      // attachments 同理，如果需要展示可转
      try {
        newItem.attachments = typeof item.attachmentName === 'string' ? JSON.parse(item.attachmentName) : [];
      } catch (err) {
        newItem.attachments = [];
      }
      return newItem;
    });
    console.log("列表数据:", hrEntryApplyList.value);
    total.value = res.total;
  } catch (error) {
    console.error('获取列表失败:', error);
    proxy?.$modal.msgError('获取列表失败');
  } finally {
    loading.value = false;
  }
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  hrEntryApplyFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  createTimeRange.value = ['', ''];
  queryFormRef.value?.resetFields();
    queryParams.value.params = {
    bUseTime: undefined,
    eUseTime: undefined,
    beginTime: undefined,
    endTime: undefined
  };
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: HrEntryApplyVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加新员工入职材料审批";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: HrEntryApplyVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getHrEntryApply(_id);
  // 处理后端入库需要的字段
  const data = { ...res.data };
  // salaryRecords -> salary
  if (Array.isArray(form.value.salaryRecords)) {
    data.salaryRecords = JSON.parse(data.salary);
  }
  // attachments -> attachmentName
  if (Array.isArray(form.value.attachments)) {
    data.attachments = JSON.parse(data.attachmentName);
  }

  Object.assign(form.value, data);
  dialog.visible = true;
  dialog.title = "修改新员工入职材料审批";
};


/** 提交按钮 */
const submitForm = () => {
  hrEntryApplyFormRef.value?.validate(async (valid: boolean) => {
    if (!valid) return;
    // 处理提交给后端的字段
    const submitData = { ...form.value };
    if (Array.isArray(submitData.salaryRecords)) {
      submitData.salary = JSON.stringify(submitData.salaryRecords);
    }
    if (Array.isArray(submitData.attachments)) {
      submitData.attachmentName = JSON.stringify(submitData.attachments);
    }
    buttonLoading.value = true;
    try {
      if (submitData.id) {
        await updateHrEntryApply(submitData);
      } else {
        await addHrEntryApply(submitData);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    } finally {
      buttonLoading.value = false;
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: HrEntryApplyVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除新员工入职材料审批编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delHrEntryApply(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('humanresource/hrEntryApply/export', {
    ...queryParams.value
  }, `hrEntryApply_${new Date().getTime()}.xlsx`)
}

// 下拉框打开时展开全部节点
const handleVisibleChange = (visible: boolean) => {
  if (visible) {
    // 展开全部节点（treeSelect 内部的 tree 是 el-tree 实例）
    setTimeout(() => {
      const tree = deptTreeSelectRef.value?.$refs?.tree;
       tree?.expandAll?.();
    }, 0);
  }
};

// 获取部门树
const fetchDeptTree = async () => {
  try {
    const res = await getDeptTree();
    const processNode = (node: any) => {
      if (node.children && node.children.length > 0) {
        // 有子节点 → 禁用，但允许展开
        node.disabled = true;
        node.children.forEach(processNode); // 递归处理子节点
      } else {
        // 叶子节点 → 可选
        node.disabled = false;
      }
    };
    if (Array.isArray(res.data)) {
      res.data.forEach(processNode);
    }
    deptTree.value = res.data;
  } catch (error) {
    console.error('获取部门树失败:', error);
    proxy?.$modal.msgError('获取部门树失败');
  }
};


// 新增一条薪资记录，最多 3 条
const addRecord = () => {
  if (form.value.salaryRecords.length >= 3) {
    ElMessage.warning('最多只能添加 3 条薪资记录');
    return;
  }
  form.value.salaryRecords.push({ salaryType: null, salaryTaxType: null, salaryAmount: null });
};

// 删除一条薪资记录，至少保留 1 条
const removeRecord = (index: number) => {
  if (form.value.salaryRecords.length <= 1) {
    ElMessage.warning('至少保留一条薪资记录');
    return;
  }
  form.value.salaryRecords.splice(index, 1);
};

onMounted(() => {
  getList();
  fetchDeptTree();
});
</script>
